package com.yupi.yupicturebackend.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yupi.yupicturebackend.Exception.BusinessException;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.Exception.ThrowUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.api.aliyunAI.AliYunAiApi;
import com.yupi.yupicturebackend.api.aliyunAI.model.CreateOutPaintingTaskResponse;
import com.yupi.yupicturebackend.api.aliyunAI.model.GetOutPaintingTaskResponse;
import com.yupi.yupicturebackend.api.imageSearch.ImageSearchApiFacade;
import com.yupi.yupicturebackend.api.imageSearch.model.ImageSearchResult;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.SpaceUserPermissionConstant;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.yupicturebackend.manager.auth.StpKit;
import com.yupi.yupicturebackend.manager.auth.annotation.SaSpaceCheckPermission;
import com.yupi.yupicturebackend.model.dto.*;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.PictureReviewStatusEnum;
import com.yupi.yupicturebackend.model.vo.PictureTagCategory;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private CosManager cosManager;
    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param request
     * @param pictureUploadRequest
     * @return
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> upLoadPicture(@RequestPart("file") MultipartFile multipartFile, HttpServletRequest request, PictureUploadRequest pictureUploadRequest) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, loginUser, pictureUploadRequest);
        return ResultUtils.success(pictureVO);
    }

    /**
     * url上传
     *
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> upLoadPictureByUrl(HttpServletRequest request, @RequestBody PictureUploadRequest pictureUploadRequest) {
        User loginUser = userService.getLoginUser(request);
        String url = pictureUploadRequest.getUrl();
        PictureVO pictureVO = pictureService.uploadPicture(url, loginUser, pictureUploadRequest);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // 判断是否登陆
        Long userId = user.getId();
        ThrowUtils.throwIf(userId == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登陆！");
        // 判断照片是否存在
        Long picTureId = deleteRequest.getId();
        if (picTureId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片id为空");
        }
        pictureService.deletePicture(picTureId, user);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片（包装类）
     */
    @PostMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(@RequestParam("id") Long id, HttpServletRequest request) {
        // 判断是否登陆
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "用户未登陆");
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在！");
        return ResultUtils.success(picture);
    }


    /**
     * vo类
     */
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间的图片，需要校验权限
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }


    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页查询接口
     * 该接口用于获取图片列表的分页查询结果，根据用户请求的页码和页大小进行查询
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> getPictureVOPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        // 获取当前页码
        long current = pictureQueryRequest.getCurrent();
        // 获取当前页大小
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫：如果请求的页大小超过20条，则视为异常请求，可能是爬虫行为
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null){
            // 查询公共图库
            // 强制设置查询参数为已过审
            pictureQueryRequest.setReviewStatus(Integer.valueOf(PictureReviewStatusEnum.PASS.getValue()));
            pictureQueryRequest.setNullSpaceId(true);
        }else{
            boolean success = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            if(!success){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
            }
//            // 获取当前用户
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在！");
//            if (!space.getUserId().equals(loginUser.getId())){
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无查看权限");
//            }
        }
        // 查询数据库：根据当前页码和页大小，以及查询条件，从数据库中获取图片数据
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));
        // 返回成功响应，包含分页查询结果
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    @Deprecated
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> getPictureVOPageByCache(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        // 获取当前页码
        long current = pictureQueryRequest.getCurrent();
        // 获取当前页大小
        long size = pictureQueryRequest.getPageSize();
        // 强制设置查询参数为已过审
        pictureQueryRequest.setReviewStatus(Integer.valueOf(PictureReviewStatusEnum.PASS.getValue()));
        // 限制爬虫：如果请求的页大小超过20条，则视为异常请求，可能是爬虫行为
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 构建缓存key
        // 把查询对象转化为json字符串然后通过md5算法算出固定的哈希值，拼接字符串获得key
        String queryObject = JSONUtil.toJsonStr(pictureQueryRequest);
        String md5Code = DigestUtils.md5DigestAsHex(queryObject.getBytes());
        String key = "yupicture:getPictureVOPage"+md5Code;
        // 多级缓存
        // 1. 先查询本地缓存caffeine，
        String Caffeine_pictureVOJson = LOCAL_CACHE.getIfPresent(key);
        if (Caffeine_pictureVOJson != null) {
            // 能查询到直接返回数据
            // 转化为page类型，泛型指定为PictureVO
            Page<PictureVO> page = JSONUtil.toBean(Caffeine_pictureVOJson, Page.class);
            return ResultUtils.success(page);
        }
        // 2. 本地缓存没有命中查询redis
        String Redis_pictureVOJson = stringRedisTemplate.opsForValue().get(key);
        if (Redis_pictureVOJson != null) {
            // redis命中返回数据
            Page<PictureVO> page = JSONUtil.toBean(Redis_pictureVOJson, Page.class);
            return ResultUtils.success(page);
        }
        // 3.没有命中任何缓存，查询数据库然后更新caffeine和redis：根据当前页码和页大小，以及查询条件，从数据库中获取图片数据
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 写入redis中,设置过期时间，防止雪崩
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(pictureVOPage),300, TimeUnit.SECONDS);
        // 写入 caffeine中
        LOCAL_CACHE.put(key, JSONUtil.toJsonStr(pictureVOPage));
        // 返回成功响应，包含分页查询结果
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }



    /**
     * 编辑图片（用户可用)
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常");
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 分类标签视图
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("猎奇", "热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常");
        }
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登陆！");

        // 实体类与dto转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // tags标签是json需要转字符串
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());

        pictureService.validPicture(picture);
        // 判断是否存在
        Long pictureId = picture.getId();
        Picture oldPicture = pictureService.lambdaQuery().eq(Picture::getId, pictureId).one();
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");


        Picture newPicture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, newPicture);
        pictureService.fillReviewingParams(newPicture, loginUser);

        boolean success = pictureService.updateById(newPicture);
        ThrowUtils.throwIf(!success, ErrorCode.OPERATION_ERROR, "更新图片失败");
        return ResultUtils.success(true);
    }


    /**
     * 图片上传（批量）
     *
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> upLoadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Integer counts = pictureService.uploadPictureByBatch(pictureUploadRequest, loginUser);
        return ResultUtils.success(counts);
    }


    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(resultList);
    }


    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }


    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }


    @Resource
    private AliYunAiApi aliYunAiApi;
    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }


}
